package com.demo.controller;

import com.google.code.kaptcha.Producer;
import com.sun.deploy.net.HttpResponse;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.awt.image.BufferedImage;
import java.io.IOException;

import static com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY;

@Controller
public class YzmController {
    @RequestMapping("/codeyanzheng")
    public String yanzhengma(HttpServletRequest req, HttpServletResponse resp, String code, Model model) throws IOException {
        //获取session中的验证码
        String token = (String) req.getSession().getAttribute(KAPTCHA_SESSION_KEY);
        req.getSession().removeAttribute(KAPTCHA_SESSION_KEY);
//        System.out.println(code);
//        System.out.println(token);
        if(token!=null&&token.equalsIgnoreCase(code)){
            model.addAttribute("msg","验证码正确");
            return "yanzhengma";
        }else {
            model.addAttribute("msg","验证码错误");
            return "yanzhengma";
        }
    }
    @RequestMapping("/code")
    public String yanzhengma(){
        return "yanzhengma";
    }
    @Resource
    private Producer producer;
    @RequestMapping("/kaptcha")
    @ResponseBody
    public void code(HttpServletResponse response,HttpServletRequest request) throws IOException {
        String code=producer.createText();
        BufferedImage image = producer.createImage(code);
        request.getSession().setAttribute("KAPTCHA_SESSION_KEY",code);
        ImageIO.write(image,"JPEG",response.getOutputStream());

    }
}
